<template>
    <div>
        <div class="container">
            <el-row>
                <el-button type="primary" icon="el-icon-video-play" @click="clickResume('divPlugin5')"
                    round>恢复</el-button>
                <el-button type="primary" icon="el-icon-video-pause" @click="clickPause('divPlugin5')"
                    round>暂停</el-button>
            </el-row>
            <el-row>
                <div id="divPlugin1" class="plugin"></div>
            </el-row>
            <!-- <el-row>
                <div id="divPlugin1" class="plugin"></div>
            </el-row> -->
            <!-- <div class="btn">
                <button id="stop" @click="clickPause('divPlugin5')">暂停</button>
                <button id="begin" @click="clickResume('divPlugin5')">恢复</button>
            </div> -->
        </div>
    </div>

</template>

<script>
export default {
    name: "hkView",
    props: {
        locationId: {
            type: [Number, String],
            default: ""
        },
        ip: {
            type: String,
            default: ""
        },
        port: {
            type: [Number, String],
            default: ""
        },
        userName: {
            type: [Number, String],
            default: ""
        },
        pwd: {
            type: [Number, String],
            default: ""
        },
        iPresetID: {
            type: [Number, String],
            default: ""
        }
    },
    data() {
        return {
            // locationId: this.locationId,
            // ip: this.ip,
            // port: this.port,
            // userName: this.userName,
            // pwd: this.pwd,
            // iPresetID: this.iPresetID,
        }
    },
    async mounted() {
        try {
            // await this.I_SupportNoPlugin();
            // await this.clickLogin("192.168.6.168", "1", "80", "admin", "Jumpin2024");

            // await this.eachList();
            // await this.I_InitPlugin("divPlugin1");
            // 此处登录的是硬盘录像机，参数为：ip、端口（服务端口）、播放窗口、是否代理、摄像头通道号
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);
            // //设置预制点
            // await this.clickSetPreset();
            // //调用预制点
            // await this.clickGoPreset();
            // this.viewInit();


            // await this.I_InitPlugin("divPlugin2");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 2);

            // await this.I_InitPlugin("divPlugin3");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 3);


            // await this.I_InitPlugin("divPlugin4");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);

            // await this.I_InitPlugin("divPlugin5");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);

            // await this.I_InitPlugin("divPlugin6");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);

            // await this.I_InitPlugin("divPlugin7");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);

            // await this.I_InitPlugin("divPlugin8");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);

            // await this.I_InitPlugin("divPlugin9");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 2);

            // await this.I_InitPlugin("divPlugin10");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);

            // await this.I_InitPlugin("divPlugin11");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);

            // await this.I_InitPlugin("divPlugin12");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);

            // await this.I_InitPlugin("divPlugin13");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);

            // await this.I_InitPlugin("divPlugin14");
            // await this.clickStartRealPlay("192.168.6.168", "80", 0, true, 1);


            // await this.I_InitPlugin("divPlugin5");
            // await this.clickStartPlayback("192.168.6.168", "80", 0, true, "2025-07-18 00:00:00", "2025-07-18 23:59:59", 1);

            // await this.I_InitPlugin("divPlugin6");
            // await this.clickStartPlayback("192.168.6.168", "80", 0, true, "2025-07-18 00:00:00", "2025-07-18 23:59:59", 2);

            // await this.I_InitPlugin("divPlugin7");
            // await this.clickStartPlayback("192.168.6.168", "80", 0, true, "2025-07-18 00:00:00", "2025-07-18 23:59:59", 3);
        } catch (e) {
            this.$notify.error({
                title: '错误',
                duration: 2000,
                message: "执行错误错"
            });
            console.error("执行错误错:", e);
        }
    },
    updated() {
    },
    watch: {
        locationId(newValue, oldValue) {
            console.log(this.ip, this.port, this.locationId)
            // 数据变化后的逻辑
            if (newValue != oldValue) {
                this.I_InitPlugin("divPlugin1");
                // 此处登录的是硬盘录像机，参数为：ip、端口（服务端口）、播放窗口、是否代理、摄像头通道号
                this.clickStartRealPlay(this.ip, this.port, 0, true, 1);
                this.clickSetPreset(0);
                this.clickGoPreset(0);
            }
        },
    },
    methods: {
        //校验是否支持无插件
        I_SupportNoPlugin() {
            return new Promise((resolve, reject) => {
                console.log(112313123)
                const iRet = window.WebVideoCtrl.I_SupportNoPlugin();
                if (!iRet) {
                    this.$notify.error({
                        title: '错误',
                        duration: 2000,
                        message: "当前浏览器版本过低，不支持无插件，请升级后再试！"
                    });
                    return reject("浏览器不支持无插件");
                }
                resolve();
            });
        },

        //初始化插件
        I_InitPlugin(divPlugin) {
            return new Promise((resolve) => {
                WebVideoCtrl.I_InitPlugin("100%", "100%", {
                    bWndFull: true,
                    iPackageType: 2,
                    iWndowType: 1,
                    bNoPlugin: true,
                    cbSelWnd: function (xmlDoc) {
                        // let index = parseInt($(xmlDoc).find("SelectWnd").eq(0).text(), 10);
                        let g_iWndIndex = WebVideoCtrl.I_GetWindowStatus(0);
                        console(WebVideoCtrl)
                        console.log("this.g_iWndIndex", g_iWndIndex);
                    },
                    cbInitPluginComplete: function () {
                        WebVideoCtrl.I_InsertOBJECTPlugin(divPlugin);
                        console.log("插件初始化完成")
                        resolve(); // 插件初始化完成时 resolve
                    },
                    cbEvent: function (iEventType, iParam1, iParam2) {
                        console.log("插件事件:", iEventType, iParam1, iParam2);
                    },
                    cbPluginErrorHandler: function (iWndIndex, iErrorCode) {
                        console.error("插件错误：", iErrorCode);
                    },
                    cbPerformanceLack: function () {
                        console.warn("性能不足！");
                    }
                });
            });
        },

        viewInit() {
            console.log(this.props)
        },

        // 登录
        clickLogin(szIP, iProtocol, szPort, szUsername, szPassword) {
            return new Promise((resolve, reject) => {
                const that = this;
                var szDeviceIdentify = szIP + "_" + szPort;

                const iRet = WebVideoCtrl.I_Login(szIP, iProtocol, szPort, szUsername, szPassword, {
                    success: function () {
                        console.log(szDeviceIdentify + " 登录成功！");
                        that.getDevicePort(szIP, szPort);
                        that.getChannelInfo(szIP, szPort);
                        resolve(); // 登录成功
                    },
                    error: function (status, xmlDoc) {
                        console.error(szDeviceIdentify + " 登录失败！", status);
                        reject("登录失败");
                    }
                });

                if (iRet === -1) {
                    console.log(szDeviceIdentify + " 已登录过！");
                    resolve(); // 已登录也继续执行
                }
            });
        },

        // 退出
        clickLogout(szIP, szPort) {
            return new Promise((resolve) => {
                var szDeviceIdentify = szIP + "_" + szPort;
                var szInfo = "";
                if (null == szDeviceIdentify) {
                    return;
                }
                let WndSet = WebVideoCtrl.I_GetWndSet()
                var iRet = WebVideoCtrl.I_Logout(szDeviceIdentify);
                if (0 == iRet) {
                    WndSet.forEach(element => {
                        if (element.szDeviceIdentify === szDeviceIdentify) {
                            WebVideoCtrl.I_Stop({
                                iIndex: element.iIndex,
                                success: function () {
                                    szInfo = "停止取流成功！";
                                    console.log(szDeviceIdentify + " " + szInfo);
                                },
                                error: function () {
                                    szInfo = "停止取流失败！";
                                    console.log(szDeviceIdentify + " " + szInfo);
                                }
                            });
                            WebVideoCtrl.I_SetSecretKey('', element.iIndex) // 清空码流秘钥   
                        }
                    });
                    szInfo = "退出成功！";
                    getChannelInfo();
                    getDevicePort();
                } else {
                    szInfo = "退出失败！";
                }
                console.log(szDeviceIdentify + " " + szInfo);
            })

        },

        // 停止录像
        clickStopRecord(szType, iWndIndex) {
            return new Promise((resolve) => {
                if ("undefined" === typeof iWndIndex) {
                    iWndIndex = g_iWndIndex;
                }
                var oWndInfo = WebVideoCtrl.I_GetWindowStatus(iWndIndex),
                    szInfo = "";

                if (oWndInfo != null) {
                    WebVideoCtrl.I_StopRecord({
                        success: function () {
                            if ('realplay' === szType) {
                                szInfo = "停止录像成功！";
                            } else if ('playback' === szType) {
                                szInfo = "停止剪辑成功！";
                            }
                            console.log(oWndInfo.szDeviceIdentify + " " + szInfo);
                        },
                        error: function () {
                            if ('realplay' === szType) {
                                szInfo = "停止录像失败！";
                            } else if ('playback' === szType) {
                                szInfo = "停止剪辑失败！";
                            }
                            console.log(oWndInfo.szDeviceIdentify + " " + szInfo);
                        }
                    });
                }
            })
        },

        // 获取通道
        getChannelInfo(szIP, szPort) {
            let that = this;
            return new Promise((resolve) => {
                var szDeviceIdentify = szIP + "_" + szPort;

                if (null == szDeviceIdentify) {
                    return;
                }

                // 数字通道
                WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify, {
                    async: false,
                    success: function (xmlDoc) {
                        var oChannels = $(xmlDoc).find("InputProxyChannelStatus");
                        $.each(oChannels, function (i) {
                            var id = $(this).find("id").eq(0).text(),
                                name = $(this).find("name").eq(0).text(),
                                ip = $(this).find("ipAddress").eq(0).text(),
                                online = $(this).find("online").eq(0).text();
                            if ("false" == online) {// 过滤禁用的数字通道
                                return true;
                            }
                            if ("" == name) {
                                name = "IPCamera " + (i < 9 ? "0" + (i + 1) : (i + 1));
                            }
                            console.log("<option value='" + id + "' bZero='false'>" + name + "</option>");

                            that.arr.push({
                                ip: ip.replace(/\./g, "_"),
                                id: id
                            })
                        });
                        console.log(szDeviceIdentify + " 获取数字通道成功！");
                    },
                    error: function (status, xmlDoc) {
                        console.log(szDeviceIdentify + " 获取数字通道失败！", status, xmlDoc);
                    }
                });
            })
        },

        // 获取端口
        getDevicePort(szIP, szPort) {
            return new Promise((resolve) => {
                var szDeviceIdentify = szIP + "_" + szPort;

                if (null == szDeviceIdentify) {
                    return;
                }

                var oPort = WebVideoCtrl.I_GetDevicePort(szDeviceIdentify);
                if (oPort != null) {
                    console.log(szDeviceIdentify + " 获取端口成功！");
                } else {
                    console.log(szDeviceIdentify + " 获取端口失败！");
                }
            })
        },

        // 开始预览
        clickStartRealPlay(szIP, szPort, g_iWndIndex, bProxy, iChannelID) {
            return new Promise((resolve, reject) => {
                const szDeviceIdentify = szIP + "_" + szPort;
                const iRtspPort = 554;
                // const iChannelID = 1;
                const bZeroChannel = false;
                const iStreamType = 1;

                const startRealPlay = () => {
                    WebVideoCtrl.I_StartRealPlay(szDeviceIdentify, {
                        iRtspPort,
                        iStreamType,
                        iChannelID,
                        bZeroChannel,
                        bProxy,
                        success: () => {
                            console.log(szDeviceIdentify + " 开始预览成功！");
                            resolve();
                        },
                        error: (status) => {
                            const msg = status === 403 ? "设备不支持Websocket取流！" : "开始预览失败！";
                            this.$notify.error({
                                title: '错误',
                                duration: 2000,
                                message: szDeviceIdentify + " " + msg
                            });
                            console.error(szDeviceIdentify + " " + msg);
                            reject(msg);
                        }
                    });
                };

                const oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);
                if (oWndInfo != null) {
                    WebVideoCtrl.I_Stop({
                        success: startRealPlay,
                        error: () => {
                            this.$notify.error({
                                title: '错误',
                                duration: 2000,
                                message: "预览停止失败，但继续尝试播放"
                            });
                            console.warn("预览停止失败，但继续尝试播放");
                            startRealPlay();
                        }
                    });
                } else {
                    startRealPlay();
                }
            });
        },

        // 开始回放
        clickStartPlayback(szIP, szPort, g_iWndIndex, bProxy, szStartTime, szEndTime, iChannelID) {
            return new Promise((resolve, reject) => {
                var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);
                const szDeviceIdentify = szIP + "_" + szPort;
                const iRtspPort = 554;
                // const iChannelID = 1;
                const bZeroChannel = false;
                const iStreamType = 1;
                var szInfo = "";
                if (null == szDeviceIdentify) {
                    return;
                }

                if (bZeroChannel) {// 零通道不支持回放
                    return;
                }

                var startPlayback = function () {
                    WebVideoCtrl.I_StartPlayback(szDeviceIdentify, {
                        iRtspPort: iRtspPort,
                        iStreamType: iStreamType,
                        iChannelID,
                        szStartTime,
                        szEndTime,
                        bProxy,  //ws取流协议是否要过Nginx
                        success: function () {
                            szInfo = "开始回放成功！";
                            console.log(szDeviceIdentify + " " + szInfo);
                            console.log("iChannelID" + " " + iChannelID);
                            resolve();
                        },
                        error: function (status, xmlDoc) {
                            if (403 === status) {
                                szInfo = "设备不支持Websocket取流！";
                            } else {
                                szInfo = "开始回放失败！";
                            }
                            console.log(szDeviceIdentify + " " + szInfo);
                            reject(szInfo);
                        }
                    });
                };

                if (oWndInfo != null) { // 已经在播放了，先停止
                    console.log("已经在播放了，先停止");
                    WebVideoCtrl.I_Stop({
                        success: function () {
                            startPlayback();
                        }
                    });
                } else {
                    startPlayback();
                }
            });
        },

        // 暂停
        clickPause(divId) {
            console.log(divId)
            var oWndInfo = WebVideoCtrl.I_GetWindowStatus(0),
                szInfo = "";

            if (oWndInfo != null) {
                WebVideoCtrl.I_Pause({
                    success: function () {
                        szInfo = "暂停成功！";
                        console.log(oWndInfo.szDeviceIdentify + " " + szInfo);
                    },
                    error: function () {
                        szInfo = "暂停失败！";
                        console.log(oWndInfo.szDeviceIdentify + " " + szInfo);
                        this.$notify.error({
                            title: '错误',
                            duration: 2000,
                            message: oWndInfo.szDeviceIdentify + " " + szInfo
                        });
                    }
                });
            }
        },

        // 恢复
        clickResume(divId) {
            var oWndInfo = WebVideoCtrl.I_GetWindowStatus(0),
                szInfo = "";
            console.log(oWndInfo)
            if (oWndInfo != null) {
                WebVideoCtrl.I_Resume({
                    success: function () {
                        szInfo = "恢复成功！";
                        console.log(oWndInfo.szDeviceIdentify + " " + szInfo);
                    },
                    error: function () {
                        szInfo = "恢复失败！";
                        this.$notify.error({
                            title: '错误',
                            duration: 2000,
                            message: oWndInfo.szDeviceIdentify + " " + szInfo
                        });
                        console.log(oWndInfo.szDeviceIdentify + " " + szInfo);
                    }
                });
            }
        },

        // 设置预置点
        clickSetPreset(g_iWndIndex) {
            var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex)
            if (oWndInfo != null) {
                WebVideoCtrl.I_SetPreset(this.iPresetID, {
                    success: function (xmlDoc) {
                        console.log(oWndInfo.szDeviceIdentify + " 设置预置点成功！");
                    },
                    error: function (status, xmlDoc) {
                        this.$notify.error({
                            title: '错误',
                            duration: 2000,
                            message: oWndInfo.szDeviceIdentify + " 设置预置点失败！", status, xmlDoc
                        });
                    }
                });
            }
        },

        // 调用预置点
        clickGoPreset(g_iWndIndex) {
            var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex)
            if (oWndInfo != null) {
                WebVideoCtrl.I_GoPreset(this.iPresetID, {
                    success: function (xmlDoc) {
                        console.log(oWndInfo.szDeviceIdentify + " 调用预置点成功！");
                    },
                    error: function (status, xmlDoc) {
                        this.$notify.error({
                            title: '错误',
                            duration: 2000,
                            message: oWndInfo.szDeviceIdentify + " 调用预置点失败！", status, xmlDoc
                        });
                    }
                });
            }
        },

        async eachList() {
            for (const [index, item] of this.arr.entries()) {
                await this.I_InitPlugin(item.ip);
                await this.clickStartRealPlay("192.168.6.168", "80", 0, true, item.id);
            }
        }
    }
}
</script>

<style>
/* .container {
    display: flex;
} */

.plugin {
    width: 620px;
    height: 400px;
    background-color: lightblue;
    margin: 3px 3px 3px 3px;
    /* 可选：间距 */
}
</style>